package com.fresher.authentication;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import com.fresher.service.LogService;

public class MyAuthenticationFailHandler implements AuthenticationFailureHandler{
    static Logger logger = LoggerFactory.getLogger(MyAuthenticationFailHandler.class);
    
    //get message from properties file
    @Autowired
	MessageSource messageSource;
    
    @Autowired
    private LogService logService;
    
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession(false);
		if(session.getAttribute("attempts")!=null) { 
			int attempts = Integer.parseInt(session.getAttribute("attempts").toString())+1;
			if(attempts>3) {
				Locale locale = LocaleContextHolder.getLocale();
//				if(locale.toLanguageTag().equals("vi")) {
//					session.setAttribute("lockalert", "Tài khoản của bạn đã bị khóa!");
//				} else {
//					session.setAttribute("lockalert", "Your account is locked!");
//				logger.info("authentication failure exceed. account locked | " + logService.getCurrentDateTime());
//				}
				String message = messageSource.getMessage("label.lock", null, locale).toString();
				session.setAttribute("lockalert", message);
			}
			session.setAttribute("attempts", attempts);
		} else {
			session.setAttribute("attempts", 1);
			logger.info("authentication failure first time. set attempt = 1 | " + logService.getCurrentDateTime());
		}
		response.sendRedirect("login?error");
		logger.info("return to login/error?  page | " + logService.getCurrentDateTime());
	}
}


